import { defineStore } from 'pinia'
import {
  listAllRolesAPI,
  addRoleAPI,
  updateRoleAPI,
  deleteRoleAPI,
  getRoleByIdAPI,
  toggleRoleStatusAPI,
  assignPermissionsAPI,
  unassignPermissionAPI,
  listAllNoPageAPI,
  searchByRoleNameAPI
} from '@/api/roleAPI'

export const useRoleStore = defineStore('role', {
  state: () => ({
    roles: [],
    total: 0,
    currentPage: 1,
    pageSize: 10,
    loading: false,
    selectedRole: null
  }),

  actions: {
    // 获取所有角色（带分页）
    async fetchRoles(page = 1, size = 10) {
      this.loading = true
      try {
        const res = await listAllRolesAPI({
          pageNo: page,
          pageSize: size
        })

        // 修改判断条件以适配后端返回的 code: 0 表示成功
        if (res && (res.code === 0 || res.code === 200) && res.data) {
          // 处理 MyBatis Plus 分页返回的数据结构
          // 后端返回的是 Page<SysRoleVO> 对象，包含 records 和 total 字段
          if (res.data && Array.isArray(res.data.records)) {
            this.roles = res.data.records
            this.total = res.data.total || 0
          } else {
            // 如果没有 records 字段或不是数组，则初始化为空
            this.roles = []
            this.total = 0
          }

          this.currentPage = page
          this.pageSize = size
        } else {
          console.error('获取角色列表失败:', res?.message || '未知错误')
          this.roles = []
          this.total = 0
        }
      } catch (error) {
        console.error('获取角色失败:', error)
        this.roles = []
        this.total = 0
      } finally {
        this.loading = false
      }
    },

    // 根据角色名搜索角色
    async searchRolesByRoleName(roleName, page = 1, size = 10) {
      this.loading = true
      try {
        const res = await searchByRoleNameAPI({
          roleName: roleName || undefined
        })

        if (res && (res.code === 0 || res.code === 200) && res.data) {
          // 处理返回的数据
          if (Array.isArray(res.data)) {
            this.roles = res.data
            this.total = res.data.length
          } else {
            this.roles = []
            this.total = 0
          }

          this.currentPage = page
          this.pageSize = size
          return { success: true }
        } else {
          console.error('搜索角色失败:', res?.message || '未知错误')
          this.roles = []
          this.total = 0
          throw new Error(res?.message || '搜索角色失败')
        }
      } catch (error) {
        console.error('搜索角色失败:', error)
        this.roles = []
        this.total = 0
        throw error
      } finally {
        this.loading = false
      }
    },

    // 新增角色
    async addRole(roleData) {
      try {
        const res = await addRoleAPI(roleData)
        if (res && (res.code === 0 || res.code === 200)) {
          await this.fetchRoles(this.currentPage, this.pageSize)
          return { success: true }
        } else {
          throw new Error(res?.message || '添加角色失败')
        }
      } catch (error) {
        console.error('新增角色失败:', error)
        throw error
      }
    },

    // 编辑角色
    async updateRole(id, roleData) {
      try {
        const res = await updateRoleAPI({
          id: id,
          saveBO: roleData
        })

        if (res && (res.code === 0 || res.code === 200)) {
          await this.fetchRoles(this.currentPage, this.pageSize)
          return { success: true }
        } else {
          throw new Error(res?.message || '更新角色失败')
        }
      } catch (error) {
        console.error('更新角色失败:', error)
        throw error
      }
    },

    // 删除角色
    async deleteRole(id) {
      try {
        const res = await deleteRoleAPI(id)
        if (res && (res.code === 0 || res.code === 200)) {
          await this.fetchRoles(this.currentPage, this.pageSize)
          return { success: true }
        } else {
          throw new Error(res?.message || '删除角色失败')
        }
      } catch (error) {
        console.error('删除角色失败:', error)
        throw error
      }
    },

    // 获取单个角色详情
    async getRoleById(id) {
      try {
        const res = await getRoleByIdAPI(id)
        if (res && (res.code === 0 || res.code === 200) && res.data) {
          this.selectedRole = res.data
          return res.data
        } else {
          throw new Error(res?.message || '获取角色详情失败')
        }
      } catch (error) {
        console.error('获取角色详情失败:', error)
        throw error
      }
    },

    // 切换角色状态
    async toggleRoleStatus(id) {
      try {
        const res = await toggleRoleStatusAPI(id)
        if (res && (res.code === 0 || res.code === 200)) {
          await this.fetchRoles(this.currentPage, this.pageSize)
          return { success: true }
        } else {
          throw new Error(res?.message || '切换角色状态失败')
        }
      } catch (error) {
        console.error('切换角色状态失败:', error)
        throw error
      }
    },
    // 获取所有权限列表（不分页）
    async getAllPermissions() {
      try {
        const res = await listAllNoPageAPI()
        if (res && (res.code === 0 || res.code === 200) && Array.isArray(res.data)) {
          return res.data
        } else {
          throw new Error(res?.message || '获取权限列表失败')
        }
      } catch (error) {
        console.error('获取权限列表失败:', error)
        throw error
      }
    },

    // 为角色分配权限
    async assignPermissions(roleId, permissionIds) {
      try {
        const res = await assignPermissionsAPI(roleId, permissionIds)
        if (res && (res.code === 0 || res.code === 200)) {
          return { success: true }
        } else {
          throw new Error(res?.message || '分配权限失败')
        }
      } catch (error) {
        console.error('分配权限失败:', error)
        throw error
      }
    },

    // 解除角色和权限的绑定
    async unassignPermission(roleId, permissionId) {
      try {
        const res = await unassignPermissionAPI(roleId, permissionId)
        if (res && (res.code === 0 || res.code === 200)) {
          return { success: true }
        } else {
          throw new Error(res?.message || '解除权限绑定失败')
        }
      } catch (error) {
        console.error('解除权限绑定失败:', error)
        throw error
      }
    },
  }
})
